import subprocess as sp
import numpy as np
import json
import sys
import os

def eval_cmp(src_path, dst_path, m):
    my = np.fromfile(src_path, dtype=np.float32)
    gt = np.fromfile(dst_path, dtype=np.float32)
    diff = np.abs(my-gt)
    equal = np.all(gt==my)
    if not equal:
        print(f"## m {m} not equal {os.path.basename(src_path)} max {np.max(my)} {os.path.basename(dst_path)} max {np.max(gt)} max_abs_diff {np.max(diff)}")
        # np.set_printoptions(threshold=np.inf)
        # print(f"{os.path.basename(src_path)} {my}")
        # print(f"{os.path.basename(dst_path)} {gt}")
        sys.exit(-1)
    else:
        print(src_path, dst_path)
        print(my, gt)
        print(f"## m {m} equal")


cast_path = os.path.realpath(sys.argv[1])
cmd="compute-sanitizer --tool memcheck ./reduce"

gt_prefix = "../../eval_gt/"
f = open(cast_path,"r") 
lines = f.readlines()
for line in lines:
    its = json.loads(line)
    m = its["m"]
    src_path, dst_path = its["src_path"], its["dst_path"]
    test_cmd = cmd.split()+[f"{m}", "1"]
    dst_my_path = gt_prefix+"reduce.bin"
    sp.run(test_cmd + [gt_prefix+src_path, gt_prefix+dst_path, dst_my_path])
    eval_cmp(dst_my_path, gt_prefix+dst_path, m)

